<?php

namespace app\service\menu;

use app\common\helper\MenuTree;
use think\Db;

class MenuService implements IMenuService
{
    public function getMenuList()
    {
        $result = Db::table('aya_menu')
            ->where('menu_is_admin', '=', 1)
            ->where('menu_status', '<>', -1)
            ->order('menu_sort asc')
            ->order('create_time desc')
            ->column('menu_id, menu_parent_id, 
            menu_name, menu_status, menu_depth, menu_page_url, 
            menu_icon, menu_sort');
        $tree = new MenuTree();
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $n => $r) {
            $result[$n]['level'] = $tree->get_level($r['menu_id'], $result);
            $result[$n]['parent_id_node'] = ($r['menu_parent_id']) ? ' class="child-of-node-' . $r['menu_parent_id'] . '"' : '';
            $result[$n]['str_manage'] = '';
            if ($r['menu_depth'] < 3) {
                $result[$n]['str_manage'] .=
                    '<a href="' . url('menu/adminmenuadd', 'parentId=' . $r['menu_id']) .
                    '" class="btn btn-success btn-xs"><i class="fa fa-plus"></i>添加子权限</a>
                ';
            }
            $result[$n]['str_manage'] .=
                '<a href="' . url('menu/adminMenuEdit', 'id=' . $r['menu_id']) .
                '" class="btn btn-primary btn-xs"><i class="fa fa-pencil"></i>编辑</a>
                ';
            $result[$n]['str_manage'] .=
                '<button class="btn btn-danger btn-xs" onclick="doDel(' . $r['menu_id'] . ')"><i class="fa fa-trash"></i>删除</button>';
            $result[$n]['is_show'] = $r['menu_status'] == 1
                ? '显示'
                : '隐藏';
            $result[$n]['color'] = $r['menu_status'] == 1
                ? 'color: #00e765'
                : 'color: #ff2222';
        }
        $str = "<tr id='node-\$menu_id' data-level='\$level' \$parent_id_node>
                    <td>\$menu_id</td>
                    <td>\$spacer  \$menu_name</td>
                    <td>\$menu_page_url</td>
                    <td>\$menu_parent_id</td>
                    <td><i class='fa \$menu_icon'></i><sapn>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\$menu_icon</sapn></td>
                    <td>\$menu_sort</td>
                    <td style='\$color'>\$is_show</td>
                    <td class='td-do'>\$str_manage</td>
                </tr>";

        $tree->init($result);
        $menu_list = $tree->get_tree(0, $str);
        return $menu_list;
    }

    /**
     * 根据Id获取数据
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getById($id)
    {
        $result = Db::table('aya_menu')->where('menu_status', '<>', -1)
            ->where('menu_id', '=', $id)
            ->find();
        return $result;
    }
}